<?php
include "header.php";
if($_COOKIE['userrole']!="1")
{
    die("admin need");
}
?>

<div class="container-fluid">
    <!--      <div class="row">-->
    <!--        <div class="col-sm-3 col-md-2 sidebar">-->
    <!--          <ul class="nav nav-sidebar">-->
    <!--            <li class="active">-->
    <!--                <a href="#">公云<span class="sr-only">(current)</span></a>-->
    <!--            </li>-->
    <!--            <li><a href="#">熙地港</a></li>-->
    <!--            <li><a href="#">望京凯德</a></li>-->
    <!--          </ul>-->
    <!---->
    <!--        </div>-->
    <div class="col-sm-12  col-md-12  main">
        <h1 class="page-header">用户
            <button id="btn_cancelCreateUser" type="button" class="btn btn-lg btn-warning pull-right" onclick="cancelCreateUser()" style="display: none">取消</button>
            <button id="btn_finish" type="button" class="btn btn-lg btn-success pull-right" onclick="finishCreateUser()" style="display: none">保存</button>
            <button id="btn_modify" type="button" class="btn btn-lg btn-success pull-right" onclick="finishModifyUser()" style="display: none">修改</button>
            <button id="btn_create" type="button" class="btn btn-lg btn-success pull-right" onclick="showCreateUserDiv()">创建</button>

        </h1>

        <div style="padding: 100px 100px 10px;display: none" id="div_createUser">
            <form class="bs-example bs-example-form" role="form" id="aboveform">

                <div class="form-group">
                    <label>用户名</label>
                    <input id="input_name" type="text" class="form-control" placeholder="请输入用户名，用于显示" onblur="checkWidgetEcho(this.id,'user','username',this.value,current_modifyuser_id,'用户名')">
                </div>



                <div class="form-group">
                    <label>电子邮箱</label>

                    <input id="input_email" type="text" name="email"   class="form-control" placeholder="请输入电子邮箱，用于登录" onblur="checkWidgetEcho(this.id,'user','email',this.value,current_modifyuser_id,'电子邮箱')">
                </div>


                <div class="input-group">
                    <label>属于角色</label>

                    <select id="select_role" class="cls_select2 form-control" name="select_role">

                    </select>

                </div>



            </form>
        </div>

        <div class="table-responsive">
            <table class="table table-striped " id="userTable" >

            </table>
        </div>
    </div>
</div>
</div>

<script>
    var tableurl="api.php?method=getUsersTable";
    var $table = $('#userTable');
    $(function(){
        $table.bootstrapTable({
            //url: "merchantTable.json",
            url:tableurl,
            dataType: "json",
            pagination: true, //分页
            singleSelect: false,
            search: true, //显示搜索框
            pageSize:10,
            columns: [
                {
                    title: 'ID',
                    field: 'id',
                    align: 'left',
                    valign: 'middle'
                },
                {
                    title: '用户名',
                    field: 'name',
                    align: 'left',
                    valign: 'middle'
                },
                {
                    title: '电子邮箱',
                    field: 'email',
                    align: 'left',
                    valign: 'middle'
                },
                {
                    title: '所属角色',
                    field: 'rolename',
                    align: 'left',
                    valign: 'middle'
                },
                {
                    title: '操作',
                    field: 'id',
                    align: 'left',
                    formatter:function(value,row,index){
                        s=e=e2=d="";

                        if(row.name!="admin")
                        {
                            e='<a href="#" mce_href="#" onclick="editU(\''+ row.id + '\',\''+row.name+'\',\''+row.email+'\',\''+row.roleid+'\')">编辑 </a>'
                            e2='<a href="#" mce_href="#" onclick="resetUPwd(\''+ row.id + '\')">重置密码 </a>'
                            d = '<a href="#" mce_href="#" onclick="delU(\''+ row.id +'\')">删除</a> ';
                        }


                        return s+e+e2+d;
                    }
                }
            ]
        });

        $('#aboveform').bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                email: {
                    validators: {
                        notEmpty: {
                            message: '邮箱地址不能为空'
                        },
                        emailAddress: {
                            message: '邮箱地址格式有误'
                        }
                    }
                }
            }
        });
    })



    $('.cls_select2').select2({width:"100%"});
    $('.cls_select2_50').select2({width:"50%"});
    $('.cls_select2_mt').select2({width:"100%",multiple: true});

    getRoles();


    function getRoles()
    {


        $.ajax({
            url:'api.php?method=getRoles',
            type:'POST', //GET
            async:true,    //或false,是否异步
            timeout:5000,    //超时时间
            dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
            beforeSend:function(xhr){
                console.log(xhr)
                console.log('发送前')
            },
            success:function(data,textStatus,jqXHR){
                //alert(data.name);
                for(o in data)
                {
                    if(data[o].id==undefined)continue;
                    $("#select_role").append("<option value='" + data[o].id + "'>&nbsp;" + data[o].name + "</option>");

                }



            },
            error:function(xhr,textStatus){
                console.log('错误')
                console.log(xhr)
                console.log(textStatus)
            },
            complete:function(){
                console.log('结束')
            }
        });




    }


    current_modifyuser_id=0;
    function editU(id,name,email,rid)
    {
        //leak floor_info, ,roles
        current_modifyuser_id = id;
        $("#input_name").val(name);
        $("#input_email").val(email);
        $("#select_role").val(rid).trigger("change");
        showModifyUserDiv();
    }



    function delU(uid)
    {
        bootbox.prompt("<font color='red'>确定要删除此用户吗？</font>（此操作不可撤销！如需删除请在下方输入“确认删除”）",function (result) {
            if(result=="确认删除")
            {
                $.ajax({
                    url:'api.php?method=delUser',
                    type:'POST', //GET
                    async:true,    //或false,是否异步
                    data:{
                        id:uid
                    },
                    timeout:5000,    //超时时间
                    dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
                    beforeSend:function(xhr){
                        console.log(xhr)
                        console.log('发送前')
                    },
                    success:function(data,textStatus,jqXHR){
                        //alert(data.name);
                        if(data.return_code=="0")
                        {

                            bootbox.alert("删除成功",function () {

                                $("#userTable").bootstrapTable('refresh',{'url':tableurl});
                            });
                        }
                        else
                        {
                            bootbox.alert("删除失败");
                        }



                    },
                    error:function(xhr,textStatus){
                        console.log('错误')
                        console.log(xhr)
                        console.log(textStatus)
                    },
                    complete:function(){
                        console.log('结束')
                    }
                });
            }
        })
    }

    function showCreateUserDiv()
    {
        $("#div_createUser").show();
        $("#btn_cancelCreateUser").show();
        $("#btn_finish").show();
        $("#btn_create").hide();
        current_modifyuser_id=0;
        $(".table-responsive").hide();
    }

    function cancelCreateUser()
    {
        $("#div_createUser").hide();
        $("#btn_cancelCreateUser").hide();
        $("#btn_finish").hide();
        $("#btn_modify").hide();
        $("#btn_create").show();

        $("#input_name").val("");
        $("#input_email").val("");

        $("#select_role").val("").trigger("change");
        $(".table-responsive").show();
    }

    function showModifyUserDiv()
    {
        $("#div_createUser").show();
        $("#btn_cancelCreateUser").show();
        $("#btn_modify").show();
        $("#btn_create").hide();
        $(".table-responsive").hide();



    }

    function checkUserInput()
    {

        $('#aboveform').data('bootstrapValidator').validate();
        if(!$('#aboveform').data('bootstrapValidator').isValid()){
            return ;
        }
        name = $("#input_name").val();


        email = $("#input_email").val();

        role=$("#select_role").val();



        if(name=="")
        {
            bootbox.alert("用户名称不能为空");
            return false;
        }
        else if(email == "")
        {
            bootbox.alert("电子邮箱不能为空",function () {

            })
            return false;
        }
        else if(role == ""|| role==null)
        {
            bootbox.alert("角色不能为空",function () {

            })
            return false;
        }
        //alert(role);
        return true;
    }

    function finishModifyUser()
    {
        bcheck=checkUserInput();
        if(!bcheck)return;
        bootbox.confirm("确定修改此用户的信息吗？",function (result) {

            if(result)
                $.ajax({
                    url:'api.php?method=modifyUser',
                    type:'POST', //GET
                    async:true,    //或false,是否异步
                    data:{
                        id:current_modifyuser_id,
                        name:name,
                        email:email,
                        role_id:role
                    },
                    timeout:5000,    //超时时间
                    dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
                    beforeSend:function(xhr){
                        console.log(xhr)
                        console.log('发送前')
                    },
                    success:function(data,textStatus,jqXHR){
                        //alert(data.name);
                        if(data.return_code=="0")
                        {
                            bootbox.alert("修改成功",function () {
                                cancelCreateUser();
                                $("#userTable").bootstrapTable('refresh',{'url':tableurl});
                            });
                        }
                        else
                        {
                            alert(data.return_msg);
                        }



                    },
                    error:function(xhr,textStatus){
                        console.log('错误')
                        console.log(xhr)
                        console.log(textStatus)
                    },
                    complete:function(){
                        console.log('结束')
                    }
                });
        })

    }

    function finishCreateUser()
    {
        bcheck=checkUserInput();
        if(!bcheck)return;

        //return;

        $.ajax({
            url:'api.php?method=addUser',
            type:'POST', //GET
            async:true,    //或false,是否异步
            data:{
                name:name,
                email:email,
                role_id:role

            },
            timeout:5000,    //超时时间
            dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
            beforeSend:function(xhr){
                console.log(xhr)
                console.log('发送前')
            },
            success:function(data,textStatus,jqXHR){
                //alert(data.name);
                if(data.return_code=="0")
                {
                    bootbox.alert("创建成功",function () {
                        cancelCreateUser();
                        $("#userTable").bootstrapTable('refresh',{'url':tableurl});
                    });
                }
                else
                {
                    if(data.return_code=="-3")
                    {
                        bootbox.alert("用户名或电子邮箱重复，请重新输入！");
                        return;
                    }

                }



            },
            error:function(xhr,textStatus){
                console.log('错误')
                console.log(xhr)
                console.log(textStatus)
            },
            complete:function(){
                console.log('结束')
            }
        });

    }


</script>
</body>
</html>
